from matplotlib import pyplot as plt
import cv2 as cv
import numpy as np
import copy
import matplotlib.pyplot as plt

filename=r'F:\AI\lena.jpg'
img=cv.imread(filename)
gray=cv.cvtColor(img,cv.COLOR_BGR2GRAY)
cv.imshow("gray",gray)
thresh,bw=cv.threshold(gray,0,0xff,cv.THRESH_OTSU)#大津算法
print('Threshold is :', thresh)

filename2=r'F:\AI\rice.jpg'
img2=cv.imread(filename2)
gray2=cv.cvtColor(img2,cv.COLOR_BGR2GRAY)
cv.imshow("gray2",gray2)
element = cv.getStructuringElement(cv.MORPH_CROSS, (3, 3))
bw = cv.morphologyEx(bw, cv.MORPH_OPEN, element)
seg = copy.deepcopy(bw)
cnts, hier = cv.findContours(seg, cv.RETR_EXTERNAL, cv.CHAIN_APPROX_SIMPLE)
count = 0
for i in range(len(cnts), 0, -1):
    c = cnts[i-1]
    area = cv.contourArea(c)
    if area < 10:
        continue
    count = count + 1
    print("blob", i, " : ", area)

    # 区域画框并标记
    x, y, w, h = cv.boundingRect(c)
    cv.rectangle(img2, (x, y), (x+w, y+h), (0, 0, 0xff), 1)
    cv.putText(img2, str(count), (x, y), cv.FONT_HERSHEY_PLAIN, 0.5, (0, 0xff, 0))

print("米粒数量： ", count)
cv.imshow("源图", img2)
cv.imshow("阈值化图", bw)


cv.waitKey()
cv.destroyAllWindows()